/*
 * 版权所有 (C) 2015-2016 上海荟医信息科技有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *		1、2016年5月16日，Hanlei创建。 
 */
package com.winmine.util;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;

public class PictureUtil {
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		try {
			zoomImageScale(new File("D:/111.jpg"), "D:/111.jpg", 150);
			cut(new FileInputStream(new File("D:/111.jpg")), "D:/111.jpg", "jpg");
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("use:" + (System.currentTimeMillis() - startTime));
	}

	/**
	 * 按指定高度 等比例缩放图片
	 * 
	 * @param imageFile
	 * @param newPath
	 * @param newWidth
	 *            新图的宽度
	 * @throws IOException
	 */
	public static void zoomImageScale(File imageFile, String newPath, int newWidth) throws IOException {
		if (!imageFile.canRead())
			return;
		BufferedImage bufferedImage = ImageIO.read(imageFile);
		if (null == bufferedImage)
			return;

		int originalWidth = bufferedImage.getWidth();
		int originalHeight = bufferedImage.getHeight();
		double scale = (double) originalWidth / (double) newWidth; // 缩放的比例

		int newHeight = (int) (originalHeight / scale);

		zoomImageUtils(imageFile, newPath, bufferedImage, newWidth, newHeight);
	}

	/**
	 * 按尺寸缩放图片
	 * 
	 * @param imageFile
	 * @param newPath
	 * @param times
	 * @throws IOException
	 */
	public static void zoomImage(File imageFile, String newPath, int width, int height) throws IOException {
		if (imageFile != null && !imageFile.canRead())
			return;
		BufferedImage bufferedImage = ImageIO.read(imageFile);
		if (null == bufferedImage)
			return;

		zoomImageUtils(imageFile, newPath, bufferedImage, width, height);
	}

	/**
	 * 等比例改变图片尺寸
	 * 
	 * @param nw
	 *            新图片的宽度
	 * @param oldImage
	 *            原图片
	 * @throws IOException
	 */
	public static void constrainProportios(int nw, String oldImage) throws IOException {
		AffineTransform transform = new AffineTransform();
		BufferedImage bis = ImageIO.read(new File(oldImage));
		int w = bis.getWidth();
		int h = bis.getHeight();
		int nh = (nw * h) / w;
		double sx = (double) nw / w;
		double sy = (double) nh / h;
		transform.setToScale(sx, sy);
		AffineTransformOp ato = new AffineTransformOp(transform, null);
		BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
		ato.filter(bis, bid);

		String newPath = StringUtils.substringBeforeLast(oldImage, ".") + "_3."
				+ StringUtils.substringAfterLast(oldImage, ".");
		ImageIO.write(bid, "jpeg", new File(newPath));
		// ImageIO.write(bid, "jpeg", response.getOutputStream());
	}

	private static void zoomImageUtils(File imageFile, String newPath, BufferedImage bufferedImage, int width,
			int height) throws IOException {

		String suffix = StringUtils.substringAfterLast(imageFile.getName(), ".");

		// 处理 png 背景变黑的问题
		if (suffix != null
				&& (suffix.trim().toLowerCase().endsWith("png") || suffix.trim().toLowerCase().endsWith("gif"))) {
			BufferedImage to = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g2d = to.createGraphics();
			to = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
			g2d.dispose();

			g2d = to.createGraphics();
			Image from = bufferedImage.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
			g2d.drawImage(from, 0, 0, null);
			g2d.dispose();

			ImageIO.write(to, suffix, new File(newPath));
		} else {
			// 高质量压缩，其实对清晰度而言没有太多的帮助
			// BufferedImage tag = new BufferedImage(width, height,
			// BufferedImage.TYPE_INT_RGB);
			// tag.getGraphics().drawImage(bufferedImage, 0, 0, width, height,
			// null);
			//
			// FileOutputStream out = new FileOutputStream(newPath); // 将图片写入
			// newPath
			// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			// JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
			// jep.setQuality(1f, true); //压缩质量, 1 是最高值
			// encoder.encode(tag, jep);
			// out.close();

			// 普通的重绘
			BufferedImage newImage = new BufferedImage(width, height, bufferedImage.getType());
			Graphics g = newImage.getGraphics();
			g.drawImage(bufferedImage, 0, 0, width, height, null);
			g.dispose();
			ImageIO.write(newImage, suffix, new File(newPath));
		}
	}

	/**
	 * 图像切割
	 * 
	 * @param srcImageFile
	 *            源图像地址
	 * @param descDir切片目标文件夹
	 * @param suffix
	 *            文件类型
	 */
	public static void cut(InputStream inputStream, String descDir, String suffix) throws IOException {
		Image img;
		ImageFilter cropFilter;
		// 读取源图像
		BufferedImage bi = ImageIO.read(inputStream);
		int srcWidth = bi.getWidth(); // 源图宽度
		int srcHeight = bi.getHeight(); // 源图高度
		// 切片宽度、切片高度、切图起始坐标X
		int destWidth, destHeight, startX;
		if (srcWidth >= srcHeight) {
			destWidth = destHeight = srcHeight;
			startX = (srcWidth - srcHeight) / 2;
		} else {
			destWidth = destHeight = srcWidth;
			startX = 0;
		}
		Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
		// 四个参数分别为图像起点坐标和宽高
		// 即: CropImageFilter(int x,int y,int width,int height)
		cropFilter = new CropImageFilter(startX, 0, destWidth, destHeight);
		img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
		BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
		Graphics g = tag.getGraphics();
		g.drawImage(img, 0, 0, null); // 绘制缩小后的图
		g.dispose();
		// 输出为文件
		ImageIO.write(tag, suffix, new File(descDir));
	}

	/**
	 * * 将字符串的编码格式转换为utf-8 * * @param str * @return Name = new *
	 * String(Name.getBytes("ISO-8859-1"), "utf-8");
	 */
	public static String toUTF8(String str) {
		if ("".equals(str)) {
			return "";
		}
		try {
			if (str.equals(new String(str.getBytes("GB2312"), "GB2312"))) {
				str = new String(str.getBytes("GB2312"), "utf-8");
				return str;
			}
		} catch (Exception exception) {
		}
		try {
			if (str.equals(new String(str.getBytes("ISO-8859-1"), "ISO-8859-1"))) {
				str = new String(str.getBytes("ISO-8859-1"), "utf-8");
				return str;
			}
		} catch (Exception exception1) {
		}
		try {
			if (str.equals(new String(str.getBytes("GBK"), "GBK"))) {
				str = new String(str.getBytes("GBK"), "utf-8");
				return str;
			}
		} catch (Exception exception3) {
		}
		
		try {
			if (str.equals(new String(str.getBytes("UTF-8"), "UTF-8"))) {
				return str;
			}
		} catch (Exception exception) {
		}
		return str;
	}

}
